package com.frikinet.lifeguard.services;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.nio.SelectChannelConnector;

import com.frikinet.lifeguard.model.PostImage;
import com.frikinet.lifeguard.util.HibernateUtil;

public class LocalHttpServer
{
	public static final int serverPort = 54136;
	
	public LocalHttpServer() throws Exception
	{
		Server server = new Server();
		
		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setHost("127.0.0.1");
		connector.setPort(serverPort);
		server.addConnector(connector);
		
		HandlerList handlers = new HandlerList();
		handlers.addHandler(new StaticFilesHandler());
		handlers.addHandler(new JpegHandler());
		handlers.addHandler(new DefaultHandler());
		server.setHandler(handlers);
		
		server.start();
	}
	
	public class JpegHandler extends AbstractHandler
	{
		private final Pattern pattern = Pattern.compile("^/(.*?)\\.jpg$");
		
		@Override
		public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
		{
			Matcher matcher = pattern.matcher(target);
			if(matcher.find())
			{
				String uid = matcher.group(1);
				PostImage image = HibernateUtil.get(PostImage.class, "uid", uid);
				if(image != null)
				{
					response.setContentType("image/jpeg");
					response.setStatus(HttpServletResponse.SC_OK);
					baseRequest.setHandled(true);
					response.getOutputStream().write(image.getImage());
				}
			}
		}
	}
	
	public class StaticFilesHandler extends AbstractHandler
	{
		private Map<String, String> mimeTypes = new HashMap<String, String>();
		
		public StaticFilesHandler()
		{
			mimeTypes.put("css", "text/css");
			mimeTypes.put("js", "text/javascript");
		}
		
		public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
		{
			String path[] = target.split("/");
			if(path.length >= 2 && path[1].equals("static"))
			{
				String file[] = path[path.length-1].split("\\.");
				String extension = file[file.length-1];
				if(mimeTypes.containsKey(extension))
				{
					String route = StringUtils.join(path, "/", 2, path.length);
					InputStream stream = this.getClass().getResourceAsStream(String.format("/com/frikinet/lifeguard/templates/%s", route));
					if(stream != null)
					{
						response.setContentType(mimeTypes.get(extension));
						response.setStatus(HttpServletResponse.SC_OK);
						baseRequest.setHandled(true);
						int b = 0;
						while((b = stream.read()) > -1)
						{
							response.getOutputStream().write(b);
						}
					}
					stream.close();
				}
			}
		}
	}
	
}
